import { trim } from "lodash";
import React, { useRef, useState, useEffect } from "react";
import PropTypes from "prop-types";
import Widget from "./Widget";
import { replaceUrlParameter } from "@redash/viz/lib/lib/DateRangeParameter";
import HtmlContent from "@redash/viz/lib/components/HtmlContent";

import videozhCN from 'video.js/dist/lang/zh-CN.json';
import 'video.js/dist/video-js.css';

function VideoWidgetHeader({ widget }) {
  const title = replaceUrlParameter(widget.getWidgetOptions("widget_title"));
  const showPortal = window.location.search.includes("show_portal") && localStorage.getItem('colorstyle_titlecolor');

  return (!!trim(title)) && (
    <div className="t-header widget clearfix"
      style={showPortal ? {
        background: localStorage.getItem('colorstyle_titleback'), 
        color: localStorage.getItem('colorstyle_titlecolor'),
        height: '40px',
      } : {height: '40px'}}
    >
      <div className="th-title" style={!!widget.getWidgetOptions("title_center") ? {textAlign:'center',float: 'middle'} : {float: 'left'}}>  
        <span style={showPortal ? {color: localStorage.getItem('colorstyle_titlecolor')} : null}>
          <HtmlContent>{title}</HtmlContent>
        </span>
      </div>
    </div>
  );
}

function VideoWidget(props) {
  const { widget } = props;
  const playerRef = useRef();
  const [refreshStartedAt, setRefreshStartedAt] = useState(widget.refreshStartedAt);

  if (!!!refreshStartedAt && !!widget.refreshStartedAt) {
    setRefreshStartedAt(widget.refreshStartedAt);
  } else if (!!refreshStartedAt && !!widget.refreshStartedAt) {
    if (refreshStartedAt.isBefore(widget.refreshStartedAt)) {
      setRefreshStartedAt(widget.refreshStartedAt);
    }
  }

  useEffect(() => {
    const auto_controls = widget.getWidgetOptions("auto_controls");
    const auto_play = widget.getWidgetOptions("auto_play");
    const auto_loop = widget.getWidgetOptions("auto_loop");
    const auto_preload = widget.getWidgetOptions("auto_preload");
    const auto_muted = widget.getWidgetOptions("auto_muted");
    const poster = widget.getWidgetOptions("poster_url");
    const url = replaceUrlParameter(widget.getWidgetOptions("url"));
    const videoOptions = {
      controls: auto_controls,
      autoplay: auto_play ? "any" : false,
      loop: auto_loop,
      preload: auto_preload ? "auto": "none", 
      muted: auto_muted,
      language: 'zh-CN',
      poster: poster,
    }
   if(url.includes("webrtc")){
    // const player = new window.ZLMRTCClient.Endpoint(
    //   {
    //       element: document.getElementById('custom-videowidget'+widget.id),// video 标签
    //       debug: true,// 是否打印日志
    //       zlmsdpUrl: url,//流地址
    //       simulcast:true,
    //       useCamera:true,
    //       audioEnable:true,
    //       videoEnable:true,
    //       recvOnly:true,
    //       autoplay:true,
    //       resolution:{w:'100%',h:'100%'}
    //   });
   }else{
    import(/* webpackChunkName:"videojs" */ 'video.js').then(({default: videojs}) => {  
      videojs.addLanguage('zh-CN', videozhCN);
      const player = videojs(playerRef.current, videoOptions, () => {
        player.src({
          src: url,
          type: /\.m3u8$/.test(url) ? 'application/x-mpegURL' : '',
        });
      });

      return () => {
        player.dispose();
      };  
    });
  }
  }, [refreshStartedAt, widget]);
  
  if (!widget.width) {
    return null;
  }

  return (    
    <Widget 
      {...props} 
      className="widget-text"
      header={<VideoWidgetHeader widget={widget} />
      }
    >
      <video ref={playerRef}  id={'custom-videowidget'+widget.id}
            controls 
            autoplay={widget.options.widgetOptions.auto_play}
        className="video-js vjs-default-skin vjs-big-play-centered"
        style={{width: "100%",height: "100%"}}
      >
      <track default kind="captions" srclang="en" /></video>
    </Widget>
  );
};

VideoWidget.propTypes = {
  widget: PropTypes.object.isRequired, // eslint-disable-line react/forbid-prop-types
};

export default VideoWidget;
